package com.jinlia.show.modules.system.config;

import com.github.shyiko.mysql.binlog.BinaryLogClient;
import com.github.shyiko.mysql.binlog.event.*;
import com.github.shyiko.mysql.binlog.event.deserialization.EventDeserializer;
import com.jinlia.show.modules.system.utils.MysqlDbUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.io.IOException;
import java.io.Serializable;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeoutException;

//@Component
public class MysqlBinlogLister {
    private static final Logger log = LoggerFactory.getLogger(MysqlBinlogLister.class);

    private BinaryLogClient client;

    @PostConstruct
    public void init() throws IOException, TimeoutException {
        /**
         * # 创建用户
         * CREATE USER binlog_user IDENTIFIED BY 'binlog#Replication2024!';
         * GRANT SELECT, REPLICATION SLAVE, REPLICATION CLIENT ON *.* TO 'binlog_user'@'%';
         * FLUSH PRIVILEGES;
         */
        String hostname = "sh-cynosdbmysql-grp-287nmtgw.sql.tencentcdb.com";
        int port = 27821;
        String username = "binlog_user";
        String password = "binlog#Replication2024!";
        // 创建 BinaryLogClient客户端
        client = new BinaryLogClient(hostname, port, username, password);
        // 这个 serviceId 不可重复
        client.setServerId(12);

        // 反序列化配置
        EventDeserializer eventDeserializer = new EventDeserializer();
        eventDeserializer.setCompatibilityMode(
                // 将日期类型的数据反序列化成Long类型
                EventDeserializer.CompatibilityMode.DATE_AND_TIME_AS_LONG
        );

        client.setEventDeserializer(eventDeserializer);
        // 通过 TableMap 事件获取 数据库名和表名

        client.registerEventListener(new BinaryLogClient.EventListener() {
            String database = "";
            String tableName = "";
            @Override
            public void onEvent(Event event) {
                EventType eventType = event.getHeader().getEventType();
                if (event.getData() instanceof TableMapEventData) {
                    TableMapEventData eventData = event.getData();
                    database = eventData.getDatabase();
                    tableName = eventData.getTable();
                    log.info("获取到的数据库名: {} 和 表名为: {}", database, tableName);
                }

                // 监听更新事件
                if (event.getData() instanceof UpdateRowsEventData) {
                    try {
                        // 获取表的列信息
                        Map<String, Object> columnInfo = MysqlDbUtils.retrieveTableColumnInfo(database, tableName);
                        // 获取更新后的数据
                        UpdateRowsEventData eventData = event.getData();
                        // 可能更新多行数据
                        List<Map.Entry<Serializable[], Serializable[]>> rows = eventData.getRows();
                        //更新只监控id
                        Object id = columnInfo.get("id");//获取id所在的索引
                        for (Map.Entry<Serializable[], Serializable[]> row : rows) {
                            Serializable[] key = row.getKey();
                            Serializable s = key[0];
                            log.info("监听到更新的数据为: {}.{}.{}", database,tableName,s);
                        }
                    } catch (Exception e) {
                        log.error("监听更新事件发生了异常 ={}", e);
                    }
                }

                // 监听插入事件
                if (event.getData() instanceof WriteRowsEventData) {
                    log.info("监听到插入事件");
                }

                // 监听删除事件
                if (event.getData() instanceof DeleteRowsEventData) {
                    log.info("监听到删除事件");
                }
            }
        });
        client.registerLifecycleListener(new BinaryLogClient.AbstractLifecycleListener() {
            @Override
            public void onConnect(BinaryLogClient client) {
                log.info("客户端连接到 mysql 服务器 client: {}", client);
            }

            @Override
            public void onCommunicationFailure(BinaryLogClient client, Exception ex) {
                log.info("客户端和 mysql 服务器 通讯失败 client: {}", client);
            }

            @Override
            public void onEventDeserializationFailure(BinaryLogClient client, Exception ex) {
                log.info("客户端序列化失败 client: {}", client);
            }

            @Override
            public void onDisconnect(BinaryLogClient client) {
                log.info("客户端断开 mysql 服务器链接 client: {}", client);
            }
        });
        // client.connect 在当前线程中进行解析binlog，会阻塞当前线程
        // client.connect(xxx) 会新开启一个线程，然后在这个线程中解析binlog
        client.connect(3000);
    }

    @PreDestroy
    public void destroy() throws IOException {
        client.disconnect();
        log.info("client.destroy");
    }
}
